const app = getApp();

Page({
  data: {
    cartList: [],
    totalPrice: 0,
    discount: 0,
    url: '',
    selectedItems: [] // 用于跟踪选中的书籍 ID
  },

  onLoad() {
    this.setData({
      url: app.imgUrl
    });
    this.getCartList(); // 页面加载时获取购物车列表
    wx.stopPullDownRefresh()
  },

  toggleSelect(event) {
    console.log(event)
    this.setData({
      selectedItems: event.detail,
    });
    this.calculateTotal(); // 计算总价和优惠
  },

  calculateTotal() {
    let totalPrice = 0;
  let discount = 0;

  this.data.cartList.forEach(item => {
    // 确保类型一致后判断 selectedItems 是否包含当前项的 bookId
    if (this.data.selectedItems.includes(String(item.bookId))) {
      totalPrice += item.price * item.quantity;
      discount += item.discount || 0; // 计算优惠
    }
  });

  this.setData({ totalPrice, discount });
  },

  getCartList() {
    const token = wx.getStorageSync('token');

    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        success: () => {
          wx.navigateTo({
            url: '/pages/user/login/login',
          });
        }
      });
      return;
    }

    wx.request({
      url: app.apiUrl + '/cart/list',
      method: 'GET',
      header: { token },
      success: (res) => {
        if (res.data.code === 1) {
          const cartList = res.data.data.cartVoList;
        const selectedItems = cartList.map(item => String(item.bookId)); // 提取所有 bookId

        this.setData({
          cartList: cartList,
          selectedItems: selectedItems, // 将所有 bookId 设置为选中状态
          totalPrice: res.data.data.totalPrice,
          discount: res.data.data.discount
        });
          console.log(cartList)
        } else {
          wx.showToast({ title: res.data.msg, icon: 'error' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误，请稍后重试', icon: 'error' });
      },
    });
  },
  onPullDownRefresh(){
    this.onLoad()
},
  increment(event) {
    const bookId = event.currentTarget.dataset.id; // 获取 bookId
    const newList = this.data.cartList.map(item => {
      if (item.bookId === bookId) {
        item.quantity += 1; // 增加数量
      }
      return item;
    });
    this.setData({ cartList: newList });
    this.updateCart(bookId, 1); // 更新后端购物车
  },

  decrement(event) {
    const bookId = event.currentTarget.dataset.id; // 获取 bookId
    this.deleteItem(bookId); // 删除购物车中的项目
  },

  updateCart(bookId, quantityChange) {
    const token = wx.getStorageSync('token');

    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'error',
      });
      return;
    }

    wx.request({
      url: app.apiUrl + '/cart/add',
      method: 'POST',
      header: {
        token: token,
      },
      data: {
        bookId,
        quantity: quantityChange,
      },
      success: (res) => {
        if (res.data.code == 1) {
          this.getCartList(); // 更新成功后重新获取购物车
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'error',
        });
      },
    });
  },

  deleteItem(bookId) {
    const token = wx.getStorageSync('token');

    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'error',
      });
      return;
    }

    wx.request({
      url: app.apiUrl + '/cart',
      method: 'PUT',
      header: {
        token: token,
      },
      data: {
        bookId,
        quantity: 1, // 删除时传 quantity 为 1
      },
      success: (res) => {
        if (res.data.code === 1) {
          this.getCartList(); // 重新获取购物车列表
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'error',
        });
      },
    });
  },

  deleteShop(e) {
    const bookId = e.currentTarget.dataset.id;
    const token = wx.getStorageSync('token');

    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'error',
      });
      return;
    }

    wx.request({
      url: app.apiUrl + '/cart/delete',
      method: 'DELETE',
      header: {
        token: token,
      },
      data: {
        bookId
      },
      success: (res) => {
        if (res.data.code === 1) {
          wx.showToast({
            title: '删除成功',
            icon: 'success',
          });
          this.getCartList(); // 重新获取购物车列表
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'error',
        });
      },
    });
  },

  clearCart() {
    const token = wx.getStorageSync('token');

    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'error',
      });
      return;
    }

    wx.request({
      url: app.apiUrl + '/cart/clear',
      method: 'DELETE',
      header: {
        token: token,
      },
      success: (res) => {
        if (res.data.code === 1) {
          wx.showToast({
            title: '购物车已清空',
            icon: 'success',
          });
          this.getCartList(); // 重新获取购物车列表
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'error',
        });
      },
    });
  },
  checkout() {
    console.log("checkout")
    const token = wx.getStorageSync('token'); 
    // 确保 bookId 和 selectedItems 中的 ID 类型一致
  const selectedItems = this.data.cartList.filter(item =>
    this.data.selectedItems.includes(String(item.bookId)) // 将 item.bookId 转换为字符串
  );
    console.log(selectedItems)
  if (selectedItems.length === 0) {
    wx.showToast({
      title: '请先选择商品',
      icon: 'none',
    });
    return;
  }
    // 将选中的 bookId 转换为整数数组
  // const orderIds = selectedItems.map(item => item.bookId);
  wx.request({ 
      url: app.apiUrl + '/orders/save', 
      method: 'POST', 
      header: { 
        token: token, 
      }, 
      data: { 
        "items": selectedItems, 
        "discount": this.data.discount 
      }, success:res=>{
        console.log(res)
        wx.navigateTo({
          url: '/pages/orders/index/index?orderId=' + res.data.data,
        });
      }
      })
    },

  goToBookDetail(event) {
    console.log(event)
    const bookId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/book/index/index?bookId=' + bookId,
    });
  }
});
